<template>
  <view class="content">
    <div class="show">
      <div class="title">今天值日人员</div>
      <u-line color="#2979ff"></u-line>
      <div class="time">{{ dateDay }}</div>
      <u-line length="50%"></u-line>
      <div class="name">{{persons}}</div>
    </div>
    <div class="func">
      <u--input
        class="text"
        placeholder="请输入屏蔽日期"
        border="bottom"
        v-model="mTag"
        clearable
      ></u--input>
      <div class="btn">
        <u-button type="primary" text="增加" @click="addTag"></u-button>
        <u-button type="error" text="删除" @click="removeTag"></u-button>
      </div>
    </div>
    <div class="tag">
      <div class="wrapper" v-for="(item, index) in tag" :key="index">
        <u-tag :text="item.name" class="label" type="success" plain></u-tag>
      </div>
    </div>

    <div class="func">
      <u--input
        class="text"
        placeholder="请输入值日生姓名"
        border="bottom"
        v-model="mName"
        clearable
      ></u--input>
      <div class="btn">
        <u-button type="primary" text="增加" @click="addTableList"></u-button>
        <u-button type="error" text="删除" @click="removeTableList"></u-button>
      </div>
    </div>

    <HM-dragSorts
      :list="list"
      :isLongTouch="false"
      :rowHeight="55"
      :listHeight="500"
      @change="change"
      @confirm="confirm"
      @onclick="onclick"
    >
      <template slot="rowContent" slot-scope="{ row }">
        <view class="row">
          <image v-if="row.icon" class="icon" :src="row.icon"></image>
          <text class="text">{{ row.name }}</text>
          <text class="date">{{ row.desc }} </text>
        </view>
      </template>
    </HM-dragSorts>
    <div class="font">
    </div>
  </view>
</template>
<script>
import dragSorts from "@/components/HM-dragSorts/HM-dragSorts.vue"; // 组件符合easycom规范，默认这个可以不写
import DateFormat from "@/common/DateFormat.js";

export default {
  components: { "HM-dragSorts": dragSorts }, // 组件符合easycom规范，默认这个可以不写
  data() {
    return {
      mTag: "",
      mName: "",
      icon: "/static/person.png",
      rawList: [],
      list: [],
      tag: [],
      dateDay: ""
    };
  },
  async mounted() {
    await this.getData();
    this.insertData();
    this.addList();
    this.timeFn();
  },
  computed: {
    persons() {
      if (this.list.length < 2) {
        return ""
      }
      if (this.dateDay !== new DateFormat(this.list[0].time).toString("yyyy-mm-dd")) {
        return "今日休息"
      }
      return [this.list[0].name, this.list[1].name].join(" 和 ")
    }
  },
  methods: {
    timeFn() {
      this.dateDay = new DateFormat().toString("yyyy-mm-dd");
    },
    addTableList() {
      this.rawList.push({ name: this.mName });
      this.insertData();
      this.addList();
    },
    removeTableList() {
      if (!this.rawList) return;

      for (let i = this.rawList.length - 1; i >= 0; --i) {
        if (this.rawList[i].name === this.mName) {
          this.rawList.splice(i, 1);
          break;
        }
      }
      this.insertData();
      this.addList();
    },
    tidyList(list) {
      return list.map((item) => {
        return {
          name: item.name,
          time: item.time,
        };
      }).filter((item) => {
        return item.name
      });
    },
    getData() {
      return Promise.all([this.getList(), this.getTag()]);
    },
    getList() {
      let data = { db: "list" };
      return new Promise((resolve, reject) => {
        this.get(data, (res) => {
          let list = res.result.data
            ? res.result.data[0].list
            : JSON.stringify([]);
          this.rawList = JSON.parse(list);
          resolve();
        });
      });
    },
    async addList() {
      if (!this.list || !this.list.length) return;

      await this.removeList();

      let list = this.tidyList(this.list);
      let data = {
        db: "list",
        data: { name: "main", list: JSON.stringify(list) },
      };

      this.add(data, (res) => {});
    },
    removeList() {
      let data = { db: "list", data: { name: "main" } };
      return new Promise((resolve, reject) => {
        this.remove(data, (res) => {
          resolve();
        });
      });
    },
    getTag() {
      let data = { db: "tag" };
      return new Promise((resolve, reject) => {
        this.get(data, (res) => {
          this.tag = res.result.data || [];
          resolve();
        });
      });
    },
    addTag() {
      if (!this.mTag) return;
      let data = { db: "tag", data: { name: this.mTag } };
      this.add(data, (res) => {
        this.getData().then(() => {
          this.insertData();
        });
      });
    },
    removeTag() {
      if (!this.mTag) return;
      let data = { db: "tag", data: { name: this.mTag } };
      this.remove(data, (res) => {
        this.getData().then(() => {
          this.insertData();
        });
      });
    },
    add(data, cb) {
      wx.cloud.callFunction({
        // 云函数名称
        name: "add",

        // 传给云函数的参数
        data,
        success: function (res) {
          cb(res);
        },
        fail: console.error,
      });
    },
    remove(data, cb) {
      wx.cloud.callFunction({
        // 云函数名称
        name: "remove",
        // 传给云函数的参数
        data,
        success: function (res) {
          cb(res);
        },
        fail: console.error,
      });
    },
    get(data, cb) {
      wx.cloud.callFunction({
        // 云函数名称
        name: "get",
        // 传给云函数的参数
        data,
        success: function (res) {
          cb(res);
        },
        fail: console.error,
      });
    },
    insertData() {
      let list = this.rawList;
      let index = 0;
      let line = 0;

      for (let i = 0; i < list.length; ++i) {
        let lastTime = list[i].time;

        if (
          lastTime &&
          lastTime < Date.now() &&
          new DateFormat(lastTime).toString("yyyy年mm月dd日") !==
            new DateFormat(Date.now()).toString("yyyy年mm月dd日")
        ) {
          continue;
        } else {
          line = i;
          break;
        }
      }

      list = list.concat(list.splice(0, line));

      for (let i = 0; i < list.length; ++i) {
        list[i].time = null;
      }

      list = list.map((item) => {
        let res = this.chooseDate(index);
        let obj = Object.assign({}, item, {
          time: res.time,
          desc: res.desc,
          icon: this.icon,
        });

        index = res.index;

        return obj;
      });

      this.list = list;
    },
    chooseDate(index) {
      for (let i = index; i < 99999; ++i) {
        let num = ~~(i / 2);
        let time = Date.now() + 1000 * 60 * 60 * 24 * (num*1);
        let desc = [
          new DateFormat(time).toString("yyyy年mm月dd日"),
          new DateFormat(time).toString("星期W"),
        ].join(" ");
        let isLawful = true;

        for (let j = 0; j < this.tag.length; ++j) {
          let tag = this.tag[j].name;
          if (tag && desc.includes(tag.trim())) {
            isLawful = false;
            break;
          }
        }
        if (isLawful) {
          return { index: i + 1, desc, time };
        }
      }

      return { index: index, desc: "", time: Date.now() };
    },
    onclick(e) {
      console.log("=== onclick start ===");
      console.log("被点击行: " + JSON.stringify(e.value));
      console.log("被点击下标: " + JSON.stringify(e.index));
      console.log("=== onclick end ===");
    },
    change(e) {
      console.log("=== change start ===");
      console.log("被拖动行: " + JSON.stringify(e.moveRow));
      console.log("原始下标：", e.index);
      console.log("移动到：", e.moveTo);
      console.log("=== change end ===");
    },
    confirm(e) {
      this.rawList = e.list;
      this.insertData();
      this.addList();
    },
  },
};
</script>
<style lang="scss" scoped>
//scoped css只在当前页生效 不影响子组件
page {
  background-color: #efeff4;
  height: 100%;
}
@media (prefers-color-scheme: dark) {
  page {
    background-color: #000000;
  }
}
.font {
  height: 50px;
}
.show {
  padding: 10px;
  .time {
    font-size: 18px;
    height: 20px;
    margin-bottom: 5px;
  }
  .name {
    font-size: 30px;
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .title {
    font-size: 34px;
    margin-bottom: 10px;
  }
}
.tag {
  display: flex;
  .wrapper {
    padding-left: 5px;
    margin-bottom: 5px;
  }
  .label {
  }
}
.content {
  height: 100%;
  overflow-y: scroll;
  .row {
    display: flex;
    flex-direction: row;
    align-items: center;
    .icon {
      width: 30px;
      height: 30px;
      border-radius: 6px;
      margin-right: 13px;
    }
    .text {
      font-size: 15px;
    }
    .date {
      font-size: 13px;
      margin-left: 30px;
    }
  }
}
.func {
  display: flex;
  height: 50px;
  margin-top: 10px;
  margin-bottom: 10px;
  align-items: center;

  .btn {
    width: 120px;
    height: 50px;
    display: flex;
  }
  .text {
    flex: 1;
  }
}
</style>
